/*
 * @Author: zgz
 * @Date: 2020-03-27 09:54:03
 * @LastEditTime: 2020-04-08 08:52:05
 * @LastEditors: zgz
 * @Description: file conten
 */
import { CoolSessionStorage } from '../coolStorage/cool-session-storage';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HttpClient } from '@angular/common/http';
import { Observable, throwError, BehaviorSubject } from 'rxjs';
import { catchError, filter, take, switchMap, tap } from 'rxjs/operators';
import { environment } from 'src/environments/environment';


/** 拦截器 */
@Injectable()
export class HeaderInterceptor implements HttpInterceptor {

    token: any;

    constructor(
        private sessionStorage: CoolSessionStorage,
        private http: HttpClient,
    ) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        this.token = this.sessionStorage.getObject('token') || {};
        //添加认证信息
        request = this.reqClone(request, this.token);

        return next.handle(request).pipe(catchError(error => {
            if (error instanceof HttpErrorResponse && error.status === 401) {
                return this.handle401Error(request, next);
            } else {
                return throwError(error);
            }
        }));
    }


    handle401Error(request: HttpRequest<any>, next: HttpHandler) {

        return this.refreshToken().pipe(
            switchMap((res: any) => {

                return next.handle(this.reqClone(request, res));
            }));
    }

    reqClone(request: HttpRequest<any>, token: any) {
        return request.clone(request.clone({ "setHeaders": { "Authorization": 'Bearer ' + token['accessToken'] } }));
    }

    refreshToken() {
        return this.http.post<any>(`${environment.Api}/services/healthscreen/identity/api/account/refresh-token`, {
            'refreshToken': this.token['refreshToken'],
            'clientId': "client-institution-h5"
        }).pipe(tap((tokens: any) => {
            this.sessionStorage.setObject('token', tokens);
        }));
    }


}